package com.kotlin.notes.reentrantlock

import java.util.concurrent.locks.ReentrantLock
import kotlin.system.measureTimeMillis

class ReentrantLockDemo


fun main() {

    val time1 = measureTimeMillis {
        singleThreadSum()
    }

    val time2 = measureTimeMillis {
        multiThreadSumNoLock()
    }

    val time3 = measureTimeMillis {
        multiThreadSumUseLock()
    }

    println("time1:$time1")
    println("time2:$time2")
    println("time3:$time3")
}


fun singleThreadSum() {
    var sum: Long = 0

    for (i in 1..100000) {
        sum += i
    }

    for (i in 100001..200000) {
        sum += i
    }

    println("singleThreadSum: $sum")
}


fun multiThreadSumNoLock() {
    var sum: Long = 0

    val t1 = Thread {
        for (i in 1..100000) {
            sum += i
        }
    }

    val t2 = Thread {
        for (i in 100001..200000) {
            sum += i
        }
    }

    t1.start()
    t2.start()
    t1.join()
    t2.join()


    println("multiThreadSumNoLock:$sum")
}

fun multiThreadSumUseLock() {
    var sum: Long = 0
    val lock = ReentrantLock()

    val t1 = Thread {
        lock.lock()
        try {
            for (i in 1..100000) {
                sum += i
            }
        } finally {
            lock.unlock()
        }
    }

    val t2 = Thread {
        lock.lock()
        try {
            for (i in 100001..200000) {
                sum += i
            }
        } finally {
            lock.unlock()
        }
    }

    t1.start()
    t2.start()
    t1.join()
    t2.join()

    println("multiThreadSumUseLock:$sum")
}
